﻿using System.Drawing.Imaging;
using System.Linq;
using Abp.Authorization;
using Abp.Extensions;
using Abp.IO.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using pandx.Mulan.Dto;
using pandx.Mulan.Helpers;
using pandx.Mulan.Storage;

namespace pandx.Mulan.Controllers
{
    public class ProfileControllerBase : MulanControllerBase
    {
        private const int MaxProfilePictureSize = 1024 * 1024 * 5;
        private readonly ITempFileCacheManager _tempFileCacheManager;

        public ProfileControllerBase(ITempFileCacheManager tempFileCacheManager)
        {
            _tempFileCacheManager = tempFileCacheManager;
        }

        [AbpAuthorize]
        [HttpPost]
        public void UploadProfilePicture(FileDto input)
        {
            var profilePictureFile = Request.Form.Files.First();
            if (profilePictureFile == null)
            {
                throw new UserFriendlyException("图像不存在");
            }

            if (profilePictureFile.Length > MaxProfilePictureSize)
            {
                throw new UserFriendlyException("裁剪图像大小超出 5MB 的限制");
            }

            byte[] bytes;
            using (var stream = profilePictureFile.OpenReadStream())
            {
                bytes = stream.GetAllBytes();
            }

            if (!ImageFormatHelper.GetRawImageFormat(bytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif))
            {
                throw new UserFriendlyException("图像格式不正确，仅支持JPG、PNG、GIF格式");
            }

            _tempFileCacheManager.SetFile(input.FileToken, bytes);
        }
    }
}